package com.qianxp.designparttern.delegate;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * DispatcherServlet
 */
public class DispatcherServlet extends HttpServlet {
    /**
     *
     */
    private static final long serialVersionUID = -4156478683278363047L;


    private static final Map<Integer, Handler> handlers = new ConcurrentHashMap<>();

    public static void addHttpHandler(int port, Handler handler) {
        handlers.put(port, handler);
    }

    public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException {
        Handler handler = handlers.get(req.getLocalPort());
        if (handler == null) {
            resp.sendError(404, "service not found.");
        }else{
            handler.hander(req, resp);
        }
    }

}